<!--
* description: 整车销售---订单发运指令
* author:xlc
* createdDate: 2020-11-20
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-show-more-btn="true"
      :callback-obj="callbackObj"
      :refresh-table-key="refreshTableKey"
    />
    <edit
      :key="editPopupsKey"
      :popups-visible="editPopupsVisible"
      :data-for-form="editRowData"
      :popups-state="editPopupsState"
      :title-name="titleName"
      @close="close1"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import { orgApis } from '@/api/vesalesapi.js'
import OneTableTemplate from '@/components/templates/oneTable'
import Edit from './edit'
import Vue from 'vue'
export default {
  name: 'OrderShipped',
  components: {
    OneTableTemplate,
    Edit
  },
  mixins: [oneTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, 'supplierMessage-edit'], () => {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      titleName: '自动发运开关',
      editRowData: {},
      editPopupsState: '',
      // 网格查询API配置对象
      apiConfig: orgApis.selectOrder,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          name: 'search', // 按钮图标样式
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey4',
          type: '',
          size: 'small',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          name: 'reset',
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey5',
          type: '',
          size: 'small',
          disabled: true,
          parentFileds: 'disabled:table',
          clickEvent: () => this.handeldata('shipment'),
          text: '发运',
          name: 'add',
          position: 'left'
        },
        // {
        //   compKey: 'btnKey5',
        //   type: '',
        //   size: 'small',
        //   disabled: true,
        //   parentFileds: 'disabled:table',
        //   clickEvent: () => this.handeldata('cancel'),
        //   text: '取消发运指令',
        //   name: 'cancel',
        //   position: 'left'
        // },
        {
          compKey: 'btnKey5',
          type: '',
          size: 'small',
          clickEvent: () => this.showEdit(),
          text: '自动发运开关',
          position: 'left'
        }
      ],
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            // 显示组件
            {
              compKey: 'compKey1',
              labelName: 'DMS订单编号：',
              codeField: 'saleOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '订单标签：',
              codeField: 'saleOrderSign',
              lookuptype: 'VE1013',
              component: () => import('@/components/org/LookupValue'),
              type: 'dropdownList',
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '销售计划号：',
              codeField: 'salePlanCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: 'VIN码：',
              codeField: 'vin',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey5',
              labelName: '订单状态：',
              codeField: 'orderStatus',
              lookuptype: 'VE1003',
              component: () => import('@/components/org/LookupValue'),
              type: 'dropdownList',
              isMust: false
            },
            {
              compKey: 'compKey7',
              labelName: '交付门店：',
              codeField: 'deliveryDlrId',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: false,
              oFields: 'deliveryDlrId,deliveryDlrShortName',
              customObj: {
                api: orgApis.ListOfDeliveryStore
              }
            }
          ],
      // 动态生成网格列
      tableCols: [
        {
          prop: 'stockName',
          label: '验收仓库', // 操作
          width: 170,
          isComponent: true,
          isColComp: true,
          comps: [
            {
              compKey: 'compKey10' + this.$utils.generateId(),
              codeField: 'stockId',
              textField: 'stockName',
              clearable: false,
              isAsync: true,
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              oFields: 'stockId,stockName',
              options: [{ stockId: '', stockName: '' }],
              rowFileds: 'disabled:orderStatusName-订单已发运|disabled:orderStatusName-车辆已发车,value:dlrId',
              isMul: false,
              customObj: {
                selectType: '1',
                // api: orgApis.ListOfCityWarehouse,
                // listQuery: {
                //   warehouseId: '6',
                //   dlrId: '42be223b451711eba2c00050569034e9',
                //   isEnable: '1',
                //   pageIndex: 1,
                //   pageSize: 500
                // }// 测试使用
                api: orgApis.ListOfCityWarehouse, listQuery: { warehouseId: '6', dlrId: '' }
              }
            }
          ]
        },
        {
          prop: 'dlrId',
          label: '门店ID', width: 120,
          hidden: true
        },
        {
          prop: 'saleOrderSignName',
          label: '订单标签', width: 120
        },
        {
          prop: 'saleOrderCode',
          label: 'DMS订单编号',
          width: 120
        },
        {
          prop: 'orderStatusName',
          label: '订单状态', width: 120
        },
        {
          prop: 'dlrShortName',
          label: '交付门店', width: 120
        },
        {
          prop: 'salePlanCode',
          label: '销售计划号', width: 120
        },
        {
          prop: 'vin',
          label: 'VIN码', width: 160
        },
        {
          prop: 'carSeriesCn',
          label: '车系', width: 120
        },
        {
          prop: 'carConfigCn',
          label: '基础车型名称', width: 120
        },
        {
          prop: 'optionalPagName',
          label: '选装包', width: 120
        },
        {
          prop: 'carColorName',
          label: '车身颜色', width: 120
        },
        {
          prop: 'carIncolorName',
          label: '内饰颜色', width: 120
        },
        {
          prop: 'caEmpName',
          label: '销售人员', width: 120
        },
        {
          prop: 'caEmpPhone',
          label: '销售人员电话', width: 120
        },
        {
          prop: 'preDeliverDate',
          label: '预计交付日期', width: 180
        },
        // {
        //   prop: 'sendManDate',
        //   label: '发运申请时间', width: 120
        // },
        {
          prop: 'sendPersionDate',
          label: '车辆发运日期', width: 180
        },
        {
          prop: 'remark',
          label: '备注'
        }
      ],
      formField: {
        saleOrderCode: '',
        saleOrderSign: '',
        salePlanCode: '',
        vin: '',
        orderStatus: '',
        deliveryDlrId: ''
      },
      // 是否使用刷新Key的方式刷新弹窗
      resetDialogKey: false,
      refreshTableKey: '',
      // 选择数据
      selectDefault: true,
      selectList: [],
      indexList: [],
      // 下拉框默认数据
      defaultdata: {},
      // 单表格模版页面组件回调事件
      callbackObj: {
        onCheckSelectChange: (selection) => {
          this.indexList = selection.reduce((pre, cur) => {
            pre.push(cur.index)
            return pre
          }, [])
          this.onCheckSelectChange1(selection)
        }
      }
    }
  },
  mounted() {
    this.$nextTick(
      () => {
        setTimeout(() => {
          this.queryTable()
        }, 500)
      }
    )
  },
  methods: {
    // 关闭自动发运
    close1(type) {
      this.close(type)
    },
    // 选择列是否生效
    getSelectable(row, index) {
      return !(row.orderStatusName !== '订单已配车')
    },
    handeldata(type) {
      this.selectList = []
      this.$refs.multipleTable.list.forEach(item => {
        this.indexList.forEach(a => {
          if (item.index === a) {
            this.selectList.push(item)
          }
        })
      })
      var arr = this.selectList
      console.log(arr)
      var isShip
      if (type === 'shipment') {
        isShip = arr.every((item) => {
          return item.orderStatusName === '订单已配车'
        })
        if (isShip) {
          this.shipment()
        } else {
          this.$message({
            type: 'info',
            message: '含有不可发运订单，请确认订单状态'
          })
        }
      } else if (type === 'cancel') {
        isShip = arr.every((item) => {
          return item.orderStatusName === '订单已发运'
        })
        if (isShip) {
          this.cancel()
        } else {
          this.$message({
            type: 'info',
            message: '含有不可取消订单，请确认订单状态'
          })
        }
      }
    },
    onCheckSelectChange1(selection) {
      var btn1 = this.tableButtons[2]
      var btn2 = this.tableButtons[3]
      const isCheck = selection && selection.length > 0
      btn1.disabled = !isCheck
      btn2.disabled = !isCheck
    },
    // 发运
    shipment() {
      this.$confirm('确认发运吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const obj = {
          carHouseCode: [],
          dlrCode: [],
          saleDlrCode: [],
          saleOrderId: [],
          saleOrderCodeC: [],
          carConfigCode: [],
          carColorCode: [],
          carIncolorCode: [],
          optionalPagCode: [],
          orderStatus: [],
          updateControlIdd: [],
          UPDATE_CONTROL_ID: [],
          stockId: [],
          stockName: [],
          vin: [],
          updateControlId: []
        }
        for (const k in this.selectList) {
          obj.orderStatus.push(this.selectList[k].orderStatus)
          obj.saleOrderId.push(this.selectList[k].saleOrderId)
          obj.updateControlIdd.push(this.selectList[k].updateControlIdd)
          obj.updateControlId.push(this.selectList[k].updateControlId)
          obj.UPDATE_CONTROL_ID.push(this.selectList[k].UPDATE_CONTROL_ID)
          obj.vin.push(this.selectList[k].vin)
          obj.stockId.push(this.selectList[k].stockId)
          obj.stockName.push(this.selectList[k].stockName)
          obj.carHouseCode.push(this.selectList[k].carHouseCode)
          obj.dlrCode.push(this.selectList[k].dlrCode)
          obj.saleDlrCode.push(this.selectList[k].saleDlrCode)
          obj.saleOrderCodeC.push(this.selectList[k].saleOrderCodeC)
          obj.carConfigCode.push(this.selectList[k].carConfigCode)
          obj.carColorCode.push(this.selectList[k].carColorCode)
          obj.carIncolorCode.push(this.selectList[k].carIncolorCode)
          obj.optionalPagCode.push(this.selectList[k].optionalPagCode)
        }
        const that = this
        const queryObj = {
          // api配置
          apiConfig: orgApis.ordershipment,
          // 条件/实体参数（变量），根据typeParam中的定义配置{}
          variables: {
            // 当前中台使用的名称有dataInfo、info，具体查看API文档
            dataInfo: obj
          }
        }
        // 转换了中台请求格式数据
        var paramD = that.$getParams(queryObj)
        // 调用中台API方法（可复用）
        that.$requestAPI(paramD).then(response => {
          this.$message({
            message: response.msg,
            duration: 2000
          })
          if (response.result === '1') {
            this.queryTable()
            this.refreshTableKey = this.$utils.generateId() + '1'
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },

    // 取消发运   OD.CAR_ID,SO.DLR_ID
    cancel() {
      this.$confirm('确认取消发运吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const obj = {
          orderStatus: [],
          CAR_ID: [],
          DLR_ID: [],
          salePlanCode: [],
          vin: [],
          updateControlIdd: [],
          UPDATE_CONTROL_ID: [],
          updateControlId: []
        }
        for (const k in this.selectList) {
          obj.vin.push(this.selectList[k].vin)
          obj.CAR_ID.push(this.selectList[k].CAR_ID)
          obj.DLR_ID.push(this.selectList[k].DLR_ID)
          obj.salePlanCode.push(this.selectList[k].salePlanCode)
          obj.orderStatus.push(this.selectList[k].orderStatus)
          obj.updateControlIdd.push(this.selectList[k].updateControlIdd)
          obj.UPDATE_CONTROL_ID.push(this.selectList[k].UPDATE_CONTROL_ID)
          obj.updateControlId.push(this.selectList[k].updateControlId)
        }
        const that = this
        const queryObj = {
          // api配置
          apiConfig: orgApis.orderShippedCancel,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: {
            // 当前中台使用的名称有dataInfo、info，具体查看API文档
            dataInfo: obj
          }
        }
        // 转换了中台请求格式数据
        var paramD = that.$getParams(queryObj)
        // 调用中台API方法（可复用）
        that.$requestAPI(paramD).then(response => {
          this.$message({
            message: response.msg,
            duration: 2000
          })
          if (response.result === '1') {
            this.queryTable()
            setTimeout(() => {
              this.refreshTableKey = this.$utils.generateId() + '1'
            }, 1000)
          }
        })
      }).catch((e) => {})
    }
  }
}
</script>
